package cn.com.xf.web.controller;

import java.io.File;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.ConfigUtil;
import cn.com.xf.common.Constants;
import cn.com.xf.common.StringUtil;
import cn.com.xf.domain.TblRegExpress;
import cn.com.xf.domain.TblRegVisitor;
import cn.com.xf.domain.TsDict;
import cn.com.xf.service.CompanyService;
import cn.com.xf.service.VisitorService;
import cn.com.xf.utils.HttpTool;
import cn.com.xf.utils.IdcardValidator;
import cn.com.xf.utils.ImageUtils;
import cn.com.xf.utils.checkPhone;
import cn.com.xf.web.PageModel;
import cn.com.xf.web.XFMappingJacksonJsonView;
import cn.com.xf.web.form.ExpressForm;
import cn.com.xf.web.form.VisitorForm;

@Controller
@RequestMapping("/visitor")
public class VisitorController extends AbstractBaseController {
	
	@Autowired
	private VisitorService visitorService;
	
	@Autowired
	private CompanyService companyService;
	
	@RequestMapping
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response, VisitorForm form) throws Exception {
		form.setTab(Constants.TAB_VISITOR);
		ModelAndView mv = new ModelAndView("/visitor/index", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}
	/**
	 * 访客登记列表
	 */
	@RequestMapping(value = "/listVisitor")
	public ModelAndView visitor_list(HttpServletRequest request, HttpServletResponse response, VisitorForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/visitor/visitor_list", Constants.FORM_COMMAND_KEY, form);
		String visittimeStartSDF = StringUtil.StringFilter(form.getVisittimeStart());
		String visittimeEndSDF = StringUtil.StringFilter(form.getVisittimeEnd());
		String username = StringUtil.StringFilter(form.getUsername());
		String vname = StringUtil.StringFilter(form.getVname());
		String vid = StringUtil.StringFilter(form.getVid());
		String visittimeStart = "",visittimeEnd = "";
		if(!visittimeStartSDF.equals("") && !visittimeEndSDF.equals("")){
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			Long visittimeStartLong = sf.parse(visittimeStartSDF).getTime();
			Long visittimeEndLong = sf.parse(visittimeEndSDF).getTime();
			if(visittimeStartLong > visittimeEndLong){
				visittimeStart = visittimeEndSDF;
				visittimeEnd = visittimeStartSDF;
			}else{
				visittimeStart = visittimeStartSDF;
				visittimeEnd = visittimeEndSDF;
			}
		}else{
			visittimeStart = visittimeStartSDF;
			visittimeEnd = visittimeEndSDF;
		}		
		form.setVisittimeStart(visittimeStart);
		form.setVisittimeEnd(visittimeEnd);
		form.setUsername(username);
		form.setVname(vname);
		form.setVid(vid.toString());
		Map<String,Integer> intraday = visitorService.visitorIntraday();
		mv.addObject("intraday", intraday);	
		Integer count = visitorService.visitorCount(username, vname, vid, visittimeStart, visittimeEnd);
		if (count == 0) {
			return mv;
		}
		// 3.分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		// 4.排序规则
		String orderByField = "VISITTIME";
		String orderByMode = "DESC";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("visittime".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "VISITTIME";
			}
			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}
		List<TblRegVisitor> list = visitorService.visitorList(begin, pageSize, orderByField, orderByMode, username, vname, vid, visittimeStart, visittimeEnd);
		mv.addObject("list", list);		
		return mv;
	}
	@RequestMapping(value = "/addVisitor")
	public ModelAndView addVisitor(HttpServletRequest request, HttpServletResponse response, VisitorForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/visitor/visitor_add", Constants.FORM_COMMAND_KEY, form);		
		List<TsDict> dict = companyService.selectDepts();
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		for(TsDict td:dict){
			Map<String , Object> map = new HashMap<String, Object>();
			map.put("dept", td.getDictname());
			list.add(map);
		}
		Map<String , Object> map = new HashMap<String, Object>();
		map.put("dept", "虎门呼叫中心");
		list.add(map);
		String dept = JSONArray.toJSONString(list);
		mv.addObject("dept",dept);
		return mv;		
	}
	
	@RequestMapping(value = "/doAddVisitor")
	public ModelAndView doAddVisitor(HttpServletRequest request, HttpServletResponse response, @Valid VisitorForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/visitor/visitor_add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		int resu = 0;
		String certtype = form.getCerttype();
		String cert = form.getCert();
		String phone = form.getPhone();
		boolean b = IdcardValidator.isValidatedAllIdcard(cert);
		if(cert.equals("") && phone.equals("")){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "身份证号码与联系电话必须填写一个！");			
			return mv;
		}
		if(!cert.equals("") && certtype.equals("0") && !b){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "身份证号码错误！");			
			return mv;			
		}
		if(!phone.equals("") && !checkPhone.isOkPhone(phone)){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "电话号码错误！");			
			return mv;
		}
		int photoresu = 3;
		String photo = form.getPhoto();
		String photoname = "visitor_"+DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")+ ".png";
		String photopath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
				+ Constants.ABSOLUTE_ROOT_IMAGE_PATH+"/";
		if(!photo.equals("")){
			boolean fb = ImageUtils.GenerateImage(photo, photopath, photoname);
			if(!fb){
				photoresu = -2;
			}else{
				form.setPhotoname(photoname);
			}
		}
		if(form.getVaudit().equals("1")){
			resu = visitorService.visitorModify(form);
		}else{
			resu = visitorService.visitorNew(form);		
		}
		if(resu == 1){				
			mv.addObject("status","SUCCESS");
		}else if(photoresu == -2){
			mv.addObject("status","SUCCESS");
			mv.addObject("msg", "部分成功，图片上传失败");
		}else{
			mv.addObject("status","FAILD");
			mv.addObject("msg", "服务器出错");
		}
		return mv;
	}
			
	
	
	@RequestMapping(value = "/doOut")	
	public ModelAndView doOut(HttpServletRequest request, HttpServletResponse response, VisitorForm form)
			throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String id = form.getVid();
		int result = visitorService.visitorOut(id);
		if(result == 0){
			map.put("status", "SUCCESS");
			map.put("msg", "重复离开");
		}else if(result == 1){
			map.put("status", "SUCCESS");
			map.put("msg", "离开通过");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;		
	}
	
	@RequestMapping(value = "/editVisitor")
	public ModelAndView editVisitor(HttpServletRequest request, HttpServletResponse response, VisitorForm form)
			throws Exception {
		TblRegVisitor visitor = visitorService.visitorById(form.getVid());
		Long nowTime = new Date().getTime();
		Long visitorTime = visitor.getVisittime().getTime();
		Long mi = 1000*60*5L;
		if((nowTime - visitorTime) < mi){
			ModelAndView mv = new ModelAndView("/visitor/visitor_edit", Constants.FORM_COMMAND_KEY, form);
			List<TsDict> dict = companyService.selectDepts();
			List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
			for(TsDict td:dict){
				Map<String , Object> map = new HashMap<String, Object>();
				map.put("dept", td.getDictname());
				list.add(map);
			}
			Map<String , Object> map = new HashMap<String, Object>();
			map.put("dept", "虎门呼叫中心");
			list.add(map);
			String dept = JSONArray.toJSONString(list);
			mv.addObject("dept",dept);
			mv.addObject("visitor",visitor);
			return mv;			
		}else{
			Map<String, String> map = new HashMap<String, String>();
			map.put("status", "FAILD");
			ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
			return mv;
		}
	}
	
	@RequestMapping(value = "/doEditVisitor")
	public ModelAndView doEditVisitor(HttpServletRequest request, HttpServletResponse response, @Valid VisitorForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/visitor/visitor_edit_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		String certtype = form.getCerttype();
		String cert = form.getCert();
		String phone = form.getPhone();
		boolean b = IdcardValidator.isValidatedAllIdcard(cert);
		if(cert.equals("") && phone.equals("")){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "身份证号码与联系电话必须填写一个！");			
			return mv;
		}
		if(!cert.equals("") && certtype.equals("0") && !b){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "身份证号码错误！");			
			return mv;			
		}
		if(!phone.equals("") && !checkPhone.isOkPhone(phone)){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "电话号码错误！");			
			return mv;
		}
		int photoresu = 0;
		String photoname = form.getPhotoname();		
		String photo = form.getPhoto();
		String photopath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
				+ Constants.ABSOLUTE_ROOT_IMAGE_PATH+"/";
		if(!photo.equals("")){
			if(photoname.equals("")){
				photoname = "visitor_"+DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")+ ".png";
			}
			boolean fb = ImageUtils.GenerateImage(photo, photopath, photoname);
			if(fb){
				form.setPhotoname(photoname);
			}else{
				photoresu = -2;				
			}
		}		
		int resu = visitorService.visitorModify(form);		
		if(resu == 1){				
			mv.addObject("status","SUCCESS");
		}else if(photoresu == -2){
			mv.addObject("status","SUCCESS");
			mv.addObject("msg", "部分成功，唯有图片上传失败！");
		}else{
			mv.addObject("status","FAILD");
			mv.addObject("msg", "服务器出错");
		}
		return mv;
	}
	
	@RequestMapping(value = "/getReg")
	@ResponseBody
	public void getReg2(HttpServletRequest request, HttpServletResponse response, String vname,String staffid) throws Exception{
		VisitorForm form = new VisitorForm();
		form.setVname(vname);
		form.setStaffid(staffid.equals("0")?"":staffid);
		if(staffid.equals("")||staffid.equals("0")){
			form.setVaudit("1");
		}
		List<TblRegVisitor> listTRV = visitorService.visitorReg(form);
		List<Map<String,Object>> listmap = new ArrayList<Map<String,Object>>();
		if(listTRV != null && listTRV.size() > 0){
			for(TblRegVisitor trv:listTRV){
				Map<String,Object> map = new HashMap<String, Object>();
				if(staffid.equals("") && trv.getStatus().equals("0")){
					map.put("label", trv.getVname()+" | "+trv.getCert()+" | "+trv.getPhone()+" | 预约访客");
					map.put("vid", trv.getVid());
					map.put("vaudit", trv.getVaudit());
				}else{
					map.put("label", trv.getVname()+" | "+trv.getCert()+" | "+trv.getPhone());	
				}
				map.put("vname", trv.getVname());
				map.put("certtype", trv.getCerttype());
				map.put("cert", trv.getCert());
				map.put("phone", trv.getPhone());
				map.put("units", trv.getUnits());
				map.put("depa", trv.getDepa());
				map.put("byvisitor", trv.getByvisitor());
				listmap.add(map);
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("datas", listmap);
		String mapStr = JSONObject.toJSONString(map);
		response.setContentType("text/javascript;charset=UTF-8");   
	    response.getWriter().write(mapStr);
	}
	/***********************************************************************************/
	
	/********************************************************************************/
	
	/**
	 * 预约登记
	 */
	/**
	 * 访客登记列表
	 */
	@RequestMapping(value = "/listAppoint")
	public ModelAndView appoint_list(HttpServletRequest request, HttpServletResponse response, VisitorForm form)
			throws Exception {
		String status = StringUtil.StringFilter(form.getStatus());
		String staffid = StringUtil.StringFilter(form.getStaffid());
		ModelAndView mv = null;
		if(status.equals("0")){
			mv = new ModelAndView("/visitor/appoint_list", Constants.FORM_COMMAND_KEY, form);
		}else if(staffid !=null){
			mv = new ModelAndView("/visitor/myAppoint_list", Constants.FORM_COMMAND_KEY, form);
		}		
		String appointtimeStartSDF = StringUtil.StringFilter(form.getAppointtimeStart());
		String appointtimeEndSDF = StringUtil.StringFilter(form.getAppointtimeEnd());		
		String vname = StringUtil.StringFilter(form.getVname());
		String vaudit = StringUtil.StringFilter(form.getVaudit());
		String appointtimeStart = "" , appointtimeEnd = "";
		if(!appointtimeStartSDF.equals("") && !appointtimeEndSDF.equals("")){
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			Long appointtimeStartLong = sf.parse(appointtimeStartSDF).getTime();
			Long appointtimeEndLong = sf.parse(appointtimeEndSDF).getTime();
			if(appointtimeStartLong > appointtimeEndLong){
				appointtimeStart = appointtimeEndSDF;
				appointtimeEnd = appointtimeStartSDF;
			}else{
				appointtimeStart = appointtimeStartSDF;
				appointtimeEnd = appointtimeEndSDF;
			}
		}else{
			appointtimeStart = appointtimeStartSDF;
			appointtimeEnd = appointtimeEndSDF;
		}
		form.setAppointtimeStart(appointtimeStart);
		form.setAppointtimeEnd(appointtimeEnd);
		form.setVname(vname);
		Integer count = visitorService.appointCount(staffid, vname,status,vaudit, appointtimeStart, appointtimeEnd);
		if (count == 0) {
			return mv;
		}
		// 3.分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		// 4.排序规则
		String orderByField = "APPOINTTIME";
		String orderByMode = "DESC";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("appointtime".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "APPOINTTIME";
			}							
			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}
		List<TblRegVisitor> list = visitorService.appointList(begin, pageSize, orderByField, orderByMode, staffid, vname, status,vaudit, appointtimeStart, appointtimeEnd);	
		mv.addObject("list", list);		
		return mv;
	}
	@RequestMapping(value = "/addAppoint")
	public ModelAndView addAppoint(HttpServletRequest request, HttpServletResponse response, VisitorForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/visitor/appoint_add", Constants.FORM_COMMAND_KEY, form);
		List<TsDict> dict = companyService.selectDepts();
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		for(TsDict td:dict){
			Map<String , Object> map = new HashMap<String, Object>();
			map.put("dept", td.getDictname());
			list.add(map);
		}
		Map<String , Object> map = new HashMap<String, Object>();
		map.put("dept", "虎门呼叫中心");
		list.add(map);
		String dept = JSONArray.toJSONString(list);
		mv.addObject("dept",dept);
		return mv;		
	}
	
	@RequestMapping(value = "/doAddAppoint")
	public ModelAndView doAddAppoint(HttpServletRequest request, HttpServletResponse response, @Valid VisitorForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/visitor/appoint_add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		String appointtimeStr = form.getAppointtime();
		if(appointtimeStr.equals("")){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "预约时间不能为空");			
			return mv;
		}
		Long nowTime = new Date().getTime();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Long appointtime = sf.parse(appointtimeStr).getTime();
		if(appointtime - nowTime < 0){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "预约时间必须大于现在时间！");			
			return mv;
		}
		int resu = 0;
		String certtype = form.getCerttype();
		String cert = form.getCert();
		String phone = form.getPhone();
		boolean b = IdcardValidator.isValidatedAllIdcard(cert);
		if(cert.equals("") && phone.equals("")){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "身份证号码与联系电话必须填写一个！");			
			return mv;
		}
		if(!cert.equals("") && certtype.equals("0") && !b){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "身份证号码错误！");			
			return mv;			
		}
		if(!phone.equals("") && !checkPhone.isOkPhone(phone)){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "电话号码错误！");			
			return mv;
		}
		resu = visitorService.appointNew(form);
		if(resu == 1){				
			mv.addObject("status","SUCCESS");
		}else{
			mv.addObject("status","FAILD");
			mv.addObject("msg", "服务器出错");
		}
		return mv;
	}
	
	@RequestMapping(value = "/doVaudit")	
	public ModelAndView doVaudit(HttpServletRequest request, HttpServletResponse response, VisitorForm form)
			throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String vaudit = visitorService.visitorById(form.getVid()).getVaudit();
		if(vaudit.equals("1")){
			map.put("status", "FAILD");
			map.put("msg", "请不要重复确定操作");
			ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
			return mv;
		}
		int result = visitorService.appointAudit(form);
		if(result == 0){
			map.put("status", "FAILD");
			map.put("msg", "服务器出错！");
		}else if(result == 1){
			map.put("status", "SUCCESS");
			map.put("msg", "确定通过！");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;		
	}
	
	@RequestMapping(value = "/doDeleteAppoint")
	public ModelAndView doDeleteAppoint(HttpServletRequest request, HttpServletResponse response, VisitorForm form)
			throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String id = form.getVid();
		TblRegVisitor trv = visitorService.visitorById(id);
		if(!trv.getStatus().equals("0")){
			map.put("status", "FAILD");
			ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
			return mv;
		}
		int result = visitorService.appointDel(id);
		if (result == 0) {
			map.put("status", "FAILD");
		} else if (result == 1) {
			map.put("status", "SUCCESS");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;
	}
	
	@RequestMapping(value = "/doAppointToVisitor")	
	public ModelAndView doAppointToVisitor(HttpServletRequest request, HttpServletResponse response, VisitorForm form)
			throws Exception {
		Map<String, String> map = new HashMap<String, String>();		
		int result = visitorService.appointToVisit(form);
		if(result == 0){
			map.put("status", "FAILD");
			map.put("msg", "服务器错误！");
		}else if(result == 1){
			map.put("status", "SUCCESS");
			map.put("msg", "登记成功！");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;		
	}
			
	@RequestMapping(value = "/editAppoint")
	public ModelAndView editAppoint(HttpServletRequest request, HttpServletResponse response, VisitorForm form)
			throws Exception {
		TblRegVisitor visitor = visitorService.visitorById(form.getVid());
		String status = visitor.getStatus();
		if(status.equals("0")){
			ModelAndView mv = new ModelAndView("/visitor/appoint_edit", Constants.FORM_COMMAND_KEY, form);
			List<TsDict> dict = companyService.selectDepts();
			List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
			for(TsDict td:dict){
				Map<String , Object> map = new HashMap<String, Object>();
				map.put("dept", td.getDictname());
				list.add(map);
			}
			Map<String , Object> map = new HashMap<String, Object>();
			map.put("dept", "虎门呼叫中心");
			list.add(map);
			String dept = JSONArray.toJSONString(list);
			mv.addObject("dept",dept);
			mv.addObject("visitor",visitor);
			return mv;
			
		}else{
			Map<String, String> map = new HashMap<String, String>();
			map.put("status", "FAILD");
			ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
			return mv;
		}
	}
	
	@RequestMapping(value = "/doEditAppoint")
	public ModelAndView doEditAppoint(HttpServletRequest request, HttpServletResponse response, @Valid VisitorForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/visitor/appoint_edit_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		String appointtimeStr = form.getAppointtime();
		if(appointtimeStr.equals("")){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "预约时间不能为空");			
			return mv;
		}
		Long nowTime = new Date().getTime();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Long appointtime = sf.parse(appointtimeStr).getTime();
		if(appointtime - nowTime < 0){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "预约时间必须大于现在时间！");			
			return mv;
		}
		String certtype = form.getCerttype();
		String cert = form.getCert();
		String phone = form.getPhone();
		boolean b = IdcardValidator.isValidatedAllIdcard(cert);
		if(cert.equals("") && phone.equals("")){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "身份证号码与联系电话必须填写一个！");			
			return mv;
		}
		if(!cert.equals("") && certtype.equals("0") && !b){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "身份证号码错误！");			
			return mv;			
		}
		if(!phone.equals("") && !checkPhone.isOkPhone(phone)){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "电话号码错误！");			
			return mv;
		}
		int resu = visitorService.appointModify(form);		
		if(resu == 1){				
			mv.addObject("status","SUCCESS");
		}else{
			mv.addObject("status","FAILD");
			mv.addObject("msg", "服务器出错");
		}
		return mv;
	}	
	
	
	/****************************************************************************/
	/**
	 * 快递登记列表
	 */
	@RequestMapping(value = "/listExpress")
	public ModelAndView express_list(HttpServletRequest request, HttpServletResponse response, ExpressForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/visitor/express_list", Constants.FORM_COMMAND_KEY, form);
		String addtimeStartSDF = StringUtil.StringFilter(form.getAddtimeStart());
		String addtimeEndSDF = StringUtil.StringFilter(form.getAddtimeEnd());
		String username = StringUtil.StringFilter(form.getUsername());
		String exnum = StringUtil.StringFilter(form.getExnum());
		String addtimeStart = "" , addtimeEnd = "";
		if(!addtimeStartSDF.equals("") && !addtimeEndSDF.equals("")){
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			Long addtimeStartLong = sf.parse(addtimeStartSDF).getTime();
			Long addtimeEndLong = sf.parse(addtimeEndSDF).getTime();
			if(addtimeStartLong > addtimeEndLong){
				addtimeStart = addtimeEndSDF;
				addtimeEnd = addtimeStartSDF;
			}else{
				addtimeStart = addtimeStartSDF;
				addtimeEnd = addtimeEndSDF;
			}
		}else{
			addtimeStart = addtimeStartSDF;
			addtimeEnd = addtimeEndSDF;
		}
		form.setExnum(exnum);;
		form.setUsername(username);
		form.setAddtimeStart(addtimeStart);
		form.setAddtimeEnd(addtimeEnd);
		int count = visitorService.expressCount(username, exnum, addtimeStart, addtimeEnd);
		if (count == 0) {
			return mv;
		}
		// 3.分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		// 4.排序规则
		String orderByField = "ADDTIME";
		String orderByMode = "DESC";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("addtime".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "ADDTIME";
			}
			if ("username".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "USERNAME";
			}
			if ("receiver".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "EXNUM";
			}
			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}
		List<TblRegExpress> list = visitorService.expressList(begin, pageSize, orderByField, orderByMode, username, exnum, addtimeStart, addtimeEnd);
		mv.addObject("list", list);		
		return mv;
	}
	@RequestMapping(value = "/addExpress")
	public ModelAndView addExpress(HttpServletRequest request, HttpServletResponse response, ExpressForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/visitor/express_add", Constants.FORM_COMMAND_KEY, form);		
		return mv;		
	}
	
	public static String sendGet(String url,String param) throws Exception{
		HttpClient httpClient = new HttpClient(new HttpClientParams(),new SimpleHttpConnectionManager(true));
		GetMethod method = null;
		try {
		String GetURL = url+URLEncoder.encode(param,"UTF-8");
			method = new GetMethod(GetURL);			
            //使用系统提供的默认的恢复策略
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
            //设置超时的时间
            method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);
            int statusCode = httpClient.executeMethod(method);            
        	method.getParams().setContentCharset("UTF-8");
        	String json = method.getResponseBodyAsString();
        	return json.toString();
		} finally {
			if(method != null) { //不要忘记释放，尽量通过该方法实现，
				method.releaseConnection();
			}
		}
	}
	public static String comCode (String exnum) throws Exception {
		String comCode = "";
		String comIdUrl = "https://www.kuaidi100.com/autonumber/autoComNum?text=";
		String comIdJSON = sendGet(comIdUrl, exnum);
		JSONParser jp = new JSONParser();
		JSONObject comidJson = (JSONObject) jp.parse(comIdJSON);
		comCode = comidJson.get("comCode")+"";
		JSONArray comautojson = (JSONArray) jp.parse(comidJson.get("auto")+"");
		if(comCode.equals("") && comautojson != null && comautojson.size() >0) {
			JSONObject comCodeJson =  (JSONObject) comautojson.get(0);
			comCode = comCodeJson.get("comCode")+"";
		}		
		return comCode;
		
	}
	public static String comName (String comCode) throws Exception {
		String comName = "";
		String comNameUrl = "https://www.kuaidi100.com/company.do?method=companyjs&number=";
		String comNJson = sendGet(comNameUrl,comCode);
		JSONParser jp = new JSONParser();
		JSONObject conNameJson = (JSONObject) jp.parse(comNJson);
		comName = conNameJson.get("name")+"";
		return comName;
		
	}
	public static String JDCheck(String exnum) throws Exception {
		String message = "";
		String jdUrl = "https://www.kuaidi100.com/query?type=jd&postid=";
		String JDJSON = sendGet(jdUrl, exnum);
		JSONParser jp = new JSONParser();
		JSONObject JDJson = (JSONObject) jp.parse(JDJSON);
		message = JDJson.get("message")+"";
		if(message == "ok") {
			return "京东物流";
		}
		return "???";
		
	}
	
		
	@RequestMapping(value = "/doAddExpress")
	public ModelAndView doAddExpress(HttpServletRequest request, HttpServletResponse response, @Valid ExpressForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/visitor/express_add_result", Constants.FORM_COMMAND_KEY, form);
		String[] num =  form.getNum();
		String username = form.getUsername();
		String userid = form.getUserid();
		List<String> list = new ArrayList<>();
		int t = 0;
		for (int i = 0; i < num.length; i++) {
			ExpressForm eform = new ExpressForm();
			String exnum = num[i];
			if(exnum != null && !exnum.equals("")){	
				t++;
				String comCode = comCode(exnum);
				String excom = "";
				if(!comCode.equals("")) {
					excom = comName(comCode);
				}else {
					excom = JDCheck(exnum);
				}
				eform.setExcompany(excom);
				eform.setExnum(exnum);
				eform.setUsername(username);
				eform.setUserid(userid);
				int r = visitorService.expressRepeatCount(exnum);
				if(r == 0) {
					visitorService.expressNew(eform);
				}else {
					list.add(exnum);
				}
			}
		}
		if(t>0 && list.size() == 0) {
			mv.addObject("status","SUCCESS");
		}else if(t>0 && t == list.size()){
			mv.addObject("status","FAILD");
			String str = "";
			for (String exnum : list) {
				if(str !=null && str.equals("")) {
					str = exnum;
				}else {
					str = str + ","+exnum;
				}
			}
			mv.addObject("msg", "重复单号:"+str);
		}else if(t>0 && list.size() > 0){
			mv.addObject("status","SUCCESS");
			String str = "";
			for (String exnum : list) {
				if(str !=null && str.equals("")) {
					str = exnum;
				}else {
					str = str + ","+exnum;
				}
			}
			mv.addObject("msg", "重复单号:"+str);
		}else {
			mv.addObject("status","FAILD");
			mv.addObject("msg", "单号不能为空！");
		}
		return mv;
	}
	
	@RequestMapping(value = "/doDeleteExpress")
	public ModelAndView doDeleteExpress(HttpServletRequest request, HttpServletResponse response, ExpressForm form)
			throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		TblRegExpress tre = visitorService.expressById(form.getExid());
		Long nowTime = new Date().getTime();
		Long addTime = tre.getAddtime().getTime();
		Long mi = 1000*60*5L;
		if(nowTime - addTime < mi){
			int result = visitorService.expressDel(form);
			if (result == 0) {
				map.put("status", "FAILD");
			} else if (result == 1) {
				map.put("status", "SUCCESS");
			}
		}else{
			map.put("status", "FAILD");
		}		
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;
	}
			
	@RequestMapping(value = "/editExpress")
	public ModelAndView editExpress(HttpServletRequest request, HttpServletResponse response, ExpressForm form)
			throws Exception {
		int id = form.getExid();
		TblRegExpress express = visitorService.expressById(id);
		Long nowTime = new Date().getTime();
		Long addTime = express.getAddtime().getTime();
		Long mi = 1000*60*5L;		
		if((nowTime - addTime) < mi){
			ModelAndView mv = new ModelAndView("/visitor/express_edit", Constants.FORM_COMMAND_KEY, form);			
			mv.addObject("express",express);
			return mv;			
		}else{
			Map<String, String> map = new HashMap<String, String>();
			map.put("status", "FAILD");
			ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
			return mv;
		}
	}
	
	@RequestMapping(value = "/doEditExpress")
	public ModelAndView doEditExpress(HttpServletRequest request, HttpServletResponse response, @Valid ExpressForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/visitor/express_edit_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}		
		if(form.getExnum().equals("")){
			mv.addObject("status","FAILD");
			mv.addObject("msg", "快递单号不能为空");
			return mv;
		}		
		int resu = visitorService.expressModify(form);		
		if(resu == 1){				
			mv.addObject("status","SUCCESS");
		}else{
			mv.addObject("status","FAILD");
			mv.addObject("msg", "修改失败");
		}
		return mv;
	}
	
	
	
}
